package models

import (
	"bigdevops/src/common"
	"bigdevops/src/config"
	"fmt"
	"github.com/google/uuid"
	"strconv"
)

var (
	caContent = `
            -----BEGIN CERTIFICATE-----
            MIIC/jCCAeagAwIBAgIBADANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDEwprdWJl
            cm5ldGVzMB4XDTIzMDgxMzEyMzIwNVoXDTMzMDgxMDEyMzIwNVowFTETMBEGA1UE
            AxMKa3ViZXJuZXRlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMsw
            C2Pp6uc5Q1hq0UsN6Hy4tmgiC9tvEQBv+HYkVE7r8vq/gYgCW82RwcxIaO+wbbXH
            FeXZmv33qD1cPkEDBPdYWP2GFtR0T52v4KivW4uZI/sz9oVww3MMuTF5gENlGklR
            G8RG3vAfI+wCW1YY0RPXYWdShvnF7KPnRpe7w3lxnTQNBCaCDdEnVvEYU8rCvyW1
            /ki1xP9T0HMD7hoYj9PmDkhyoWlB2AaCv7cFPotVnNunXEYLU3Ylga5e/3DGgOqi
            NYqErKGGbrmUMeFq7EUd4IQ1JK5Fqtfsgek49N9osfXELqC5Us7WXkTUgIoeheqd
            jwJ/nr17HiyApR3GctECAwEAAaNZMFcwDgYDVR0PAQH/BAQDAgKkMA8GA1UdEwEB
            /wQFMAMBAf8wHQYDVR0OBBYEFFQB986cY/7AIm2CJ4/sbyQTSKMxMBUGA1UdEQQO
            MAyCCmt1YmVybmV0ZXMwDQYJKoZIhvcNAQELBQADggEBAGjFNLsBcpOd4X57ACNW
            kZDVUgKyML3XuKyFrQVfCk70B+q8LY/n737uvzeffVzFOOKs+C0k3G4e202jvAl5
            uS9ytpzv2xbOWt5mmoHTjDSq77yk+GWm2Ek8HUm38fQmFTFDsICcgOL4uXEuObo9
            NR/IFL21aFqIb6pxSI0lxRZ0TUSKFQ93EAtCXbHass3icn7jjPMdMWvEqFAloqpZ
            JCYGoE4LndRPQFK707v/e+lpWs0x9jBe3XQsPidgABK8fEI8Xim46ucd7ud4L+gS
            ffn8/mYZJc7TiWsHXAnG3YxcfSTdpn37y1BszoQxvGqG19VYVkQIf1W5TaYQAI91
            s2Y=
            -----END CERTIFICATE-----
`
	k8sCadvisorRelabels = `
- action: replace
  regex: (.+)
  source_labels:
  - __meta_kubernetes_pod_annotation_prometheus_io_path
  target_label: __metrics_path__
- action: replace
  regex: ([^:]+)(?::\d+)?;(\d+)
  replacement: $1:$2
  source_labels:
  - __address__
  - __meta_kubernetes_pod_annotation_prometheus_io_port
  target_label: __address__
- action: labelmap
  regex: __meta_kubernetes_pod_label_(.+)
- action: replace
  source_labels:
  - __meta_kubernetes_namespace
  target_label: kubernetes_namespace
- action: replace
  source_labels:
  - __meta_kubernetes_pod_name
  target_label: kubernetes_pod_name
`
)

func MockMonitor(sc *config.ServerConfig) {

	// 新建一个采集池

	randTagKeys := []string{"arch", "idc", "os", "job", "env", "cluster", "type"}
	randTagValues := []string{"linux", "beijing", "windows", "shanghai", "arm64", "amd64", "darwin", "shijihulian"}

	num := 1
	//ips := []string{"192.168.0.181", "192.168.0.182"}
	//ips := []string{"192.168.0.81", "192.168.0.82"}
	ips := []string{"192.168.0.81"}
	// 采集池
	for i := 0; i < num; i++ {

		tags := []string{}
		for _, tagKey := range randTagKeys {
			tagValue := randTagValues[common.Frn(len(randTagValues)-1)]
			oneTag := fmt.Sprintf("%s=%s", tagKey, tagValue)
			tags = append(tags, oneTag)
		}

		p := MonitorScrapePool{
			Name:                 fmt.Sprintf("pool-%v", i),
			UserID:               1,
			PrometheusInstances:  ips,
			ScrapeInterval:       15,
			ScrapeTimeout:        10,
			ExternalLabels:       tags,
			RemoteWriteUrl:       "http://192.168.0.81:8428/api/v1/write",
			RemoteTimeoutSeconds: 5,
			SupportAlert:         common.GORM_ENBALE_RES_YES,
			SupportRecord:        common.GORM_ENBALE_RES_YES,
			RemoteReadUrl:        "http://192.168.0.81:8428/api/v1/read",
			AlertManagerUrl:      "192.168.0.81:9093",
			RuleFilePath:         "/opt/app/prometheus/rule.yml",
			RecordFilePath:       "/opt/app/prometheus/record.yml",
		}
		err := p.CreateOne()
		fmt.Printf("模拟创建采集池结果:%v err\n", err)

	}

	// 采集任务
	treeNodes, _ := GetStreeNodeAllLeaf()
	treeNodeIds := []string{}

	for _, treeNode := range treeNodes {
		treeNode := treeNode
		treeNodeIds = append(treeNodeIds, fmt.Sprintf("%d", treeNode.ID))
	}

	exporterNames := []string{"kafka", "redis", "mysqld"}
	num = 3
	for i := 0; i < num; i++ {
		j := i
		if j >= len(treeNodes) {
			j = len(treeNodes) - 1
		}
		k := i
		if k >= len(exporterNames) {
			k = len(exporterNames) - 1
		}

		scrapeJobHttp := MonitorScrapeJob{
			Name:                 fmt.Sprintf("%v-exporter-%v", exporterNames[k], i),
			UserID:               1,
			Enable:               1,
			ServiceDiscoveryType: common.MONITOR_SCRAPE_JOB_SD_TYPE_HTTP,
			MetricsPath:          "/metrics",
			Scheme:               "http",
			ScrapeInterval:       15,
			RefreshInterval:      30,
			ScrapeTimeout:        5,
			Port:                 9200,
			TreeNodeIds:          []string{treeNodeIds[j]},
			PoolId:               1,
		}

		scrapeJobHttp.CreateOne()

	}
	// 采集k8s的job

	num = 1
	for i := 0; i < num; i++ {
		scrapeJobK8s := MonitorScrapeJob{
			Name:                     fmt.Sprintf("k8s-pod-%v", i),
			Enable:                   1,
			UserID:                   1,
			ServiceDiscoveryType:     common.MONITOR_SCRAPE_JOB_SD_TYPE_K8S,
			KubernetesSdRole:         "pod",
			BearerTokenFile:          "/opt/app/prometheus/k8s-cluster-token",
			KubeconfigFilePath:       "/root/.kube/config",
			TlsCaFilePath:            "/etc/kubernetes/pki/ca.crt",
			MetricsPath:              "/metrics",
			Scheme:                   "http",
			ScrapeInterval:           15,
			RefreshInterval:          30,
			ScrapeTimeout:            5,
			PoolId:                   1,
			RelabelConfigsYamlString: k8sCadvisorRelabels,
		}
		scrapeJobK8s.CreateOne()
	}

	// 新建 cron pool

	num = 1
	for i := 0; i < num; i++ {

		p := MonitorAlertmanagerPool{
			Name:                  fmt.Sprintf("online-%v", i),
			UserID:                1,
			AlertmanagerInstances: ips,
			ResolveTimeout:        "30m",
			GroupWait:             "5s",
			GroupInterval:         "5s",
			RepeatInterval:        "15s",
			GroupBy:               []string{"alertname"},
			Receiver:              "default",
		}
		err := p.CreateOne()
		fmt.Printf("模拟创建alertmanager池结果:%v err\n", err)

	}
	num = 5

	// 值班组
	users, _ := GetUserAll()

	for i := 0; i < num; i++ {
		dutyGroup := MonitorOndutyGroup{
			Name:           fmt.Sprintf("值班组-%v", i),
			UserID:         1,
			ShiftDays:      i + 1,
			Members:        users,
			Key:            "",
			CreateUserName: "",
		}
		dutyGroup.CreateOne()

	}

	// 创建发送组

	for i := 0; i < num; i++ {
		sendGroup := MonitorSendGroup{
			Name:                fmt.Sprintf("sre-%v", i),
			NameZh:              fmt.Sprintf("运维组-%v", i),
			Enable:              1,
			UserID:              1,
			FirstUpgradeUsers:   users,
			UpgradeMinutes:      20,
			PoolId:              uint(1),
			SendResolved:        1,
			NeedUpgrade:         1,
			RepeatInterval:      "30s",
			OnDutyGroupId:       1,
			FeishuQunRobotToken: "979668be-b032-4dd5-9b98-25f9407d107f",
		}
		sendGroup.CreateOne()
	}
	metricNames := []string{

		`node_memory_Active_bytes`,
		`node_boot_time_seconds`,
		`node_uname_info`,
	}
	ruleNames := []string{
		`机器cpu使用率大于60%`,
		`kafka集群内存剩余小于2G`,
		`k8s-pending-pod数量大于5千`,
	}

	//recordNames := []string{
	//	`rec`,
	//	`kafka集群内存剩余小于2G`,
	//	`k8s-pending-pod数量大于5千`,
	//}
	severitys := []string{
		common.MONITOR_ALERT_SEVERITY_CRITICAL,
		common.MONITOR_ALERT_SEVERITY_WARNING,
		common.MONITOR_ALERT_SEVERITY_INFO,
	}
	num = 3
	// rule 文件
	for i := 0; i < num; i++ {

		mIndex := i
		if mIndex >= len(metricNames) {
			mIndex = len(metricNames) - 1
		}
		treeNodeId, _ := strconv.Atoi(treeNodeIds[common.Frn(len(treeNodeIds)-1)])
		rule := MonitorAlertRule{
			Name:        ruleNames[mIndex],
			UserID:      1,
			Enable:      1,
			PoolId:      1,
			TreeNodeId:  uint(treeNodeId),
			Severity:    severitys[common.Frn(len(severitys)-1)],
			GrafanaLink: "http://192.168.0.81:3000/d/ce3cfe66-0bb3-4b9c-aa5e-9447a4d8f30e/39ca5a93-48ec-54c1-8b16-81405fbc5902?orgId=1",
			SendGroupId: 1,
			Expr:        fmt.Sprintf(`%s >0`, metricNames[mIndex]),
			ForTime:     "1s",
			Labels:      []string{"k1=v1", "k2=v2", fmt.Sprintf("mock_label_key_%s=mock_label_value_%s", i, i)},
			Annotations: []string{

				fmt.Sprintf("%s=%s",
					common.MONITOR_RULE_ANNO_VALUE,
					"{{ $value }}"),
				"k3=v3",
				"k4=v4",
				fmt.Sprintf("mock_anno_key_%v=mock_anno_value_%v", i, i)},
		}
		rule.CreateOne()
	}

	// 预聚合规则
	num = 3
	// rule 文件
	abc := []string{
		"a",
		"b",
		"c",
	}
	for i := 0; i < num; i++ {

		mIndex := i
		if mIndex >= len(metricNames) {
			mIndex = len(metricNames) - 1
		}
		treeNodeId, _ := strconv.Atoi(treeNodeIds[common.Frn(len(treeNodeIds)-1)])
		rule := MonitorRecordRule{
			Name:       fmt.Sprintf("mock-record-%v", i+1),
			RecordName: fmt.Sprintf("node_avg_cpu_usage_%v", abc[mIndex]),
			UserID:     1,
			Enable:     1,
			PoolId:     1,
			TreeNodeId: uint(treeNodeId),
			Expr:       `avg by (instance) (1 - avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[2m])) ) * 10`,
			ForTime:    "30s",
		}
		rule.CreateOne()
	}

	///*	num = 10
	//	ago := -30
	//
	//	for i := 0; i < num; i++ {
	//		startDay := common.GetDayAgoDate(ago)
	//		userIndex := common.Frn(len(users) - 1)
	//		userId := users[userIndex].ID
	//		history := MonitorOndutyHistory{
	//			OndutyGroupId: 1,
	//			DateString:    startDay,
	//			OnDutyUserId:  userId,
	//		}
	//		history.CreateOne()
	//		ago += 1
	//*/
	//	}
	day1 := "2023-11-17"
	day2 := "2023-11-16"
	num = 5
	for i := 1; i <= num; i++ {

		h1 := MonitorOndutyHistory{
			OndutyGroupId: uint(i),
			DateString:    day1,
			OnDutyUserId:  1,
		}
		h1.CreateOne()

		h2 := MonitorOndutyHistory{
			OndutyGroupId: uint(i),
			DateString:    day2,
			OnDutyUserId:  1,
		}
		h2.CreateOne()
		//ago += 1

	}

	num = 20
	rules, _ := GetMonitorAlertRuleAll()
	sendGroups, _ := GetMonitorSendGroupAll()
	for i := 1; i <= num; i++ {
		tags := []string{}
		for _, tagKey := range randTagKeys {
			tagValue := randTagValues[common.Frn(len(randTagValues)-1)]
			oneTag := fmt.Sprintf("%s=%s", tagKey, tagValue)
			tags = append(tags, oneTag)
		}
		e := MonitorAlertEvent{
			AlertName:   fmt.Sprintf("mock-告警-%v", i),
			Fingerprint: uuid.New().String(),
			Status:      common.MONITOR_ALERT_STATUS_ARRAY[common.Frn(len(common.MONITOR_ALERT_STATUS_ARRAY)-1)],
			RuleId:      rules[common.Frn(len(rules)-1)].ID,
			SendGroupId: sendGroups[common.Frn(len(sendGroups)-1)].ID,
			EventTimes:  i * 20,
			SilenceId:   uuid.New().String(),
			Labels:      tags,
		}

		e.CreateOne()

		//ago += 1

	}
}
